package com.ruoyi.financial.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.financial.domain.FCarUse;
import com.ruoyi.financial.service.IFCarUseService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.financial.domain.FCarCost;
import com.ruoyi.financial.service.IFCarCostService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 费用支出Controller
 * 
 * @author xunzhe
 * @date 2024-03-13
 */
@Controller
@RequestMapping("/financial/fCarCost")
public class FCarCostController extends BaseController
{
    private String prefix = "financial/fCarCost";

    @Autowired
    private IFCarCostService fCarCostService;

    @Autowired
    private IFCarUseService fCarUseService;

    @RequiresPermissions("financial:fCarCost:view")
    @GetMapping()
    public String fCarCost()
    {
        return prefix + "/fCarCost";
    }

    /**
     * 查询费用支出列表
     */
    @RequiresPermissions("financial:fCarCost:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(FCarCost fCarCost)
    {
        startPage();
        List<FCarCost> list = fCarCostService.selectFCarCostList(fCarCost);
        return getDataTable(list);
    }

    /**
     * 导出费用支出列表
     */
    @RequiresPermissions("financial:fCarCost:export")
    @Log(title = "费用支出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(FCarCost fCarCost)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> dataParams = fCarCost.getParams();
        String createTimeStr = "";
        if(dataParams!=null && dataParams.get("beginTime")!=null && !dataParams.get("beginTime").toString().equals("")){
            createTimeStr = dataParams.get("beginTime").toString().split("-")[0];
        }else{
            String formattedDate = sdf.format(new Date());
            Map<String, Object> newdataParams = new HashMap<>();
            newdataParams.put("beginTime",formattedDate.split("-")[0]+"-01-01");
            newdataParams.put("endTime",formattedDate.split("-")[0]+"-12-31");
            fCarCost.setParams(newdataParams);
            createTimeStr = formattedDate.split("-")[0];
        }

        FCarCost newfCarCost = new FCarCost();
        newfCarCost.setCarNumber(fCarCost.getCarNumber());
        newfCarCost.setParams(fCarCost.getParams());
        List<FCarCost> list = fCarCostService.selectFCarCostList(newfCarCost);

        FCarUse newcarUse = new FCarUse();
        newcarUse.setCarNumber(fCarCost.getCarNumber());

        List<FCarUse> carUseList = fCarUseService.selectFCarUseList(newcarUse);
        Map returnMap = fCarCostService.exportData(list,carUseList);
        returnMap.put("createByDept",getSysUser().getDept().getDeptName());
        returnMap.put("createTime",createTimeStr);
        try {
            TemplateExportParams params = new TemplateExportParams(RuoYiConfig.getUploadPath() + "/excelmoban/caruse.xlsx");
            Workbook workbook = ExcelExportUtil.exportExcel(params, returnMap);
            String fileName = "公务用车使用管理台账.xlsx";
            String downloadPath = RuoYiConfig.getDownloadPath() + fileName;
            File desc = new File(downloadPath);
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(downloadPath);
            workbook.write(fos);
            fos.close();
            return AjaxResult.success(fileName);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 新增费用支出
     */
    @GetMapping("/add/{carId}")
    public String add(@PathVariable("carId") Long carId, ModelMap mmap)
    {
        mmap.put("carId", carId);
        return prefix + "/add";
    }

    /**
     * 新增保存费用支出
     */
    @RequiresPermissions("financial:fCarCost:add")
    @Log(title = "费用支出", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(FCarCost fCarCost)
    {
        fCarCost.setCreateBy(getLoginName());
        fCarCost.setDeptId(getSysUser().getDeptId());
        return toAjax(fCarCostService.insertFCarCost(fCarCost));
    }

    /**
     * 修改费用支出
     */
    @RequiresPermissions("financial:fCarCost:edit")
    @GetMapping("/edit/{costId}")
    public String edit(@PathVariable("costId") Long costId, ModelMap mmap)
    {
        FCarCost fCarCost = fCarCostService.selectFCarCostByCostId(costId);
        mmap.put("fCarCost", fCarCost);
        return prefix + "/edit";
    }

    /**
     * 修改保存费用支出
     */
    @RequiresPermissions("financial:fCarCost:edit")
    @Log(title = "费用支出", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(FCarCost fCarCost)
    {
        return toAjax(fCarCostService.updateFCarCost(fCarCost));
    }

    /**
     * 删除费用支出
     */
    @RequiresPermissions("financial:fCarCost:remove")
    @Log(title = "费用支出", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(fCarCostService.deleteFCarCostByCostIds(ids));
    }

    @RequiresPermissions("financial:fCarCost:detail")
    @GetMapping("/view/{costId}")
    public String fCar(@PathVariable("costId") Long costId, ModelMap mmap)
    {
        FCarCost fCarCost = fCarCostService.selectFCarCostByCostId(costId);
        mmap.put("fCarCost", fCarCost);
        return prefix + "/view";
    }

}
